package com.alex.mda.jdbc.meta;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Table {

    private String name;

    private String remarks;

    private String catalogName;

    private String schemaName;

    public Table(String name, String catalogName, String schemaName) throws SQLException {
        this.name = name;
        this.catalogName = catalogName;
        this.schemaName = schemaName;
    }

    public Table(String name, String catalogName) throws SQLException {
        this.name = name;
        this.catalogName = catalogName;
        this.schemaName = "%";
    }

    public String getName() {
        return name;
    }

    public Map<String, Column> getColumns(Connection conn) throws SQLException {
        Map<String, Column> columns = new LinkedHashMap<String, Column>();

        ResultSet rs = conn.getMetaData().getColumns(catalogName, schemaName, this.name, "%");
        while (rs.next()) {
            String colName = rs.getString("COLUMN_NAME");
            Column column = new Column(colName);
            column.setRemarks(rs.getString("REMARKS"));
            column.setSqlType(rs.getInt("DATA_TYPE"));//java.sql.Types
            columns.put(colName, column);
        }
        return columns;
    }

    public List<String> getPrimaryKeyNames(Connection conn) throws SQLException {
        List<String> names = new ArrayList<String>();

        ResultSet rs = conn.getMetaData().getPrimaryKeys(catalogName, schemaName, this.name);
        while (rs.next()) {
            String name = rs.getString("COLUMN_NAME");
            names.add(name);
        }
        return names;
    }

    public String getRemarks() {
        return remarks;
    }

    public void setRemarks(String remarks) {
        this.remarks = remarks;
    }

}
